package com.fgba.express.security;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.fgba.express.data.entity.User;
import com.fgba.express.data.service.IUserService;
import com.fgba.express.util.BeanContextUtil;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class WeChatAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        IUserService userService = BeanContextUtil.getBean(IUserService.class);

        if (authentication.isAuthenticated()) {
            return authentication;
        }
        //获取过滤器封装的token信息
        WeChatAuthenticationToken authenticationToken = (WeChatAuthenticationToken) authentication;
        String openid = (String) authenticationToken.getPrincipal();
        //根据微信id查询用户
        User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getWxId, openid));

        // 不通过
        if (user == null) {
            throw new BadCredentialsException("微信授权openid无效，请重新登陆");
        }
        String[] permissionCodes = StringUtils.tokenizeToStringArray(
                userService.getUserAuthorityInfo(user.getId()), ",");
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String permissionCode : permissionCodes) {
            if (permissionCode != null && !"".equals(permissionCode)) {
                GrantedAuthority grantedAuthority =
                        new SimpleGrantedAuthority(permissionCode);
                authorities.add(grantedAuthority);
            }
        }
        WeChatAuthenticationToken authenticationResult = new WeChatAuthenticationToken(openid, authorities);

        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return WeChatAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
